package com.desire.test;


import java.util.concurrent.TimeUnit;

/**
 * @author LittleDesire
 * @description
 * @date 2022-02-09 周三 10:04
 * @since 17
 */
public class _48_interrupt打断 {
    // 方法一的退出标志
    public static volatile boolean exit = false;


    /**
     * 方法三  .isInterrupted()判断线程的状态
     */
    public static void main(String[] args) {

        //开启线程
        var t = new Thread(_48_interrupt打断::work, "T1");
        t.start();

        try {
            System.out.println(Thread.currentThread().getName() + " 开始, 睡眠5s后打断T1线程");
            TimeUnit.SECONDS.sleep(5);
            t.interrupt();
            //true
            System.out.println("线程是否被中断：" + t.isInterrupted());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static void work() {
        Thread tt = Thread.currentThread();
        String tn = tt.getName();
        System.out.printf("%s工作线程启动了%n", tn);
        System.out.printf("%s.isInterrupted() 是否被打断:%s%n", tn, tt.isInterrupted());
        while (!tt.isInterrupted()) {
            System.out.printf("%s.isInterrupted() %s%n", tn, tt.isInterrupted());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                break;
            }

        }
        System.out.printf("%s.isInterrupted() %s%n", tn, tt.isInterrupted());
        System.out.printf("%s结束了...%n", tn);
    }


    /**
     * 方法二 interrupt();方法
     */
    public static void main2(String[] args) {
        Thread t = new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " 开始运行");
            while (true) {
                try {
                    // 每隔 500 毫秒 循环打印线程的名字
                    System.out.println(Thread.currentThread().getName() + " 运行....");
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + "被中断了");
                    break;
                }
            }
        }, "线程A");


        t.start();
        try {
            // main 线程运行两秒后 线程A 被打断 t.interrupt()
            System.out.println(Thread.currentThread().getName() + " 开始运行");
            TimeUnit.SECONDS.sleep(2);
            t.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

    /**
     * 方法一  给一个退出的标志
     */
    public static void main1(String[] args) throws InterruptedException {
        new Thread(() -> {
            System.out.println("线程启动了..");
            while (!exit) {
                //Thread.sleep(500);
                System.out.println(Thread.currentThread().getName() + " 运行中...");
            }
            System.out.println("线程结束..");
        }, "A线程").start();

        //1秒后更改退出标志的值,没有这段代码，线程就一直不能停止
        Thread.sleep(3000);
        exit = true;
    }
}
